package com.mti.zhpt.controller;

import com.mti.zhpt.form.MultiFileEntry;
import com.mti.zhpt.shared.core.ret.RetResponse;
import com.mti.zhpt.shared.core.ret.RetResult;
import com.mti.zhpt.shared.utils.FdfsClient;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(path = "/file")
public class FileController {

	@Resource
	private FdfsClient fdfsClient;

	@PostMapping(value = "/uploadBatch", consumes = "multipart/form-data")
	public RetResult query(@RequestParam("uploadFile") MultipartFile[] files) {
		MultiFileEntry result = null;
		try {
			Assert.notNull(files, "上传图片文件不能为空");
			 result = new MultiFileEntry();
			StringBuilder imagesUrl = new StringBuilder();
			StringBuilder audiosUrl = new StringBuilder();
			StringBuilder videosUrl = new StringBuilder();
			Map<String, String> map = new HashMap<String, String>();
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getOriginalFilename();
				if (fileName.endsWith(".png") || fileName.endsWith(".jpg")|| fileName.endsWith(".JPEG")) {
					imagesUrl.append(",").append(fdfsClient.uploadFile(files[i]));
				} else if (fileName.endsWith(".mp4")) {
					videosUrl.append(",").append(fdfsClient.uploadFile(files[i]));
				} else if (fileName.endsWith(".wav")) {
					audiosUrl.append(",").append(fdfsClient.uploadFile(files[i]));
				}
			}
			if (!"".equals(imagesUrl.toString())) {
				result.setImagesUrl(imagesUrl.toString().substring(1));
			}
			if (!"".equals(audiosUrl.toString())) {
				result.setAudiosUrl(audiosUrl.toString().substring(1));
			}
			if (!"".equals(videosUrl.toString())) {
				result.setVideosUrl(videosUrl.toString().substring(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return RetResponse.makeOKCp(result);
	}

}
